package com.yby6.web.controller.system;

import com.pig4cloud.captcha.ArithmeticCaptcha;
import com.pig4cloud.captcha.base.Captcha;
import com.yby6.common.exception.CustomException;
import com.yby6.common.exception.user.UserPasswordNotMatchException;
import com.yby6.common.utils.StringUtils;
import com.yby6.common.utils.ip.IpUtils;
import com.yby6.system.service.SysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import com.yby6.common.annotation.RateLimiter;
import com.yby6.common.annotation.RepeatSubmit;
import com.yby6.common.constant.Constants;
import com.yby6.common.core.AjaxResult;
import com.yby6.common.core.redis.RedisUtils;
import com.yby6.common.enums.LimitType;
import com.yby6.common.enums.ResultEnum;
import com.yby6.common.satoken.LoginHelper;
import com.yby6.common.core.domain.ActiveUser;
import com.yby6.framework.web.service.SysLoginService;
import com.yby6.common.core.domain.SysUser;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @program: yangbuyi-rbac
 * @ClassName: SysUserController
 * @create: 2021-05-13 16:48
 * @author: Yang Shuai
 * @since： JDK1.8
 * @SysUserController: 用户登陆映射$
 **/

@RestController
@Slf4j
@RequestMapping("/sysLogin")
@RequiredArgsConstructor
public class SysLoginController {

    private final SysLoginService sysLoginService;

    private final SysUserService sysUserService;

    /**
     * 用户登陆接口
     *
     * @return AjaxResult
     */
    @PostMapping("/login")
    @RateLimiter
    @RepeatSubmit(interval = 10,timeUnit = TimeUnit.SECONDS)
    public AjaxResult doLogin (@RequestBody SysUser sysUser, HttpServletRequest request) {
        if (StringUtils.isNull(sysUser) || StringUtils.isBlank(sysUser.getUsername()) || StringUtils.isBlank(sysUser.getPassword())) {
            throw new UserPasswordNotMatchException();
        }
        Serializable login = sysLoginService.login(sysUser,request);
        return AjaxResult.success().addParam("token", login);
    }

    /**
     * 获取用户信息
     *
     * @return AjaxResult
     */
    @GetMapping("/getUserInfo")
    @RateLimiter(count = 10,limitType = LimitType.IP)
    @RepeatSubmit
    public AjaxResult getUserInfo (HttpServletRequest request) {
        ActiveUser currentActiveUser = LoginHelper.getSysUser();
        SysUser sysUser = currentActiveUser.getSysUser();
        sysUser.setPassword("");
        List<String> permissions = currentActiveUser.getPermissions();
        List<String> roles = currentActiveUser.getRoles();
        log.info("请求IP:{}", IpUtils.getIpRequest(request));
        log.info("获取用户信息user:{}", sysUser);
        log.info("获取用户信息permission:{}", permissions);
        log.info("获取用户信息roles:{}", roles);
        return AjaxResult.success().addParam("user", sysUser).addParam("permissions", permissions).addParam("roles", roles);
    }

    /**
     * 登出
     *
     * @return AjaxResult
     */
    @GetMapping("/logout")
    public AjaxResult logout (HttpServletRequest request) {
        sysLoginService.logout();
        return AjaxResult.error(ResultEnum.SUCCESS.getCode(), "退出成功");
    }

    /**
     * 图形验证码
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/captcha")
    @RateLimiter(count = 10)
    @RepeatSubmit(interval = 5,timeUnit = TimeUnit.SECONDS)
    public void captcha (String randomStr, HttpServletResponse response) {
        // 算术类型
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48);
        captcha.setCharType(Captcha.FONT_1);
        // 几位数运算，默认是两位
        final String verCode = captcha.text();
        // 存入redis并设置过期时间为60s
        RedisUtils.setCacheObject(Constants.CAPTCHA_CODE_KEY + randomStr, verCode, Duration.ofSeconds(60L));
        // 输出
        try {
            captcha.out(response.getOutputStream());
        } catch (IOException e) {
            log.error("验证码初始化异常:{}", e.getCause().getMessage());
            throw new CustomException("验证码初始化异常,请联系管理员");
        }
    }

}
